package com.wfcm.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: liu
 * @Date: 2018/7/9 15:12
 * @Description: 登陆工具类
 */
@Service
public class ISsoLoginHelper {

    private static final Logger logger = LoggerFactory.getLogger(ISsoLoginHelper.class);

    private static final String LOGIN_USER_KEY_ = "LOGIN_USER_KEY_";
    private static final String LOGIN_TOKEN_KEY_ = "LOGIN_TOKEN_KEY_";

    private static JedisPool myJedisPool;

    @Autowired
    private JedisPool jedisPool;

    @PostConstruct
    public void init() {
        myJedisPool = jedisPool;
    }

    /**
     * 保存用户登陆信息
     *
     * @param userid
     * @return
     */
    public static String login(Integer userid) {
        Jedis jedis = myJedisPool.getResource();
        Map<Integer, String> map = new HashMap();
        String token = UUID.randomUUID().toString();
        try {
            jedis.hset(LOGIN_USER_KEY_ + userid, token, (System.currentTimeMillis() / 1000) + "");
            jedis.set(LOGIN_TOKEN_KEY_ + token, userid + "");
            Set<String> keys = jedis.hkeys(LOGIN_USER_KEY_ + userid);
            if (keys.size() == 4) {
                for (String key : keys) {
                    map.put(Integer.valueOf(jedis.hget(LOGIN_USER_KEY_ + userid, key)), key);
                }
                String delKey = map.get(Collections.min(map.keySet()));
                jedis.hdel(LOGIN_USER_KEY_ + userid, delKey);
                jedis.del(LOGIN_TOKEN_KEY_ + delKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
        return token;
    }


    /**
     * 保存用户登陆信息
     *
     * @param userid
     * @return
     */
    public static String loginGetToken(Integer userid) {
        Jedis jedis = myJedisPool.getResource();
        String token = "";
        try {
            Set<String> keys = jedis.hkeys(LOGIN_USER_KEY_ + userid);
            if(keys.size()>0){
                token = keys.iterator().next();
                System.out.println("**********************iterator--token:"+token);
            }else {
                token = UUID.randomUUID().toString();
                jedis.hset(LOGIN_USER_KEY_ + userid, token, (System.currentTimeMillis() / 1000) + "");
                jedis.set(LOGIN_TOKEN_KEY_ + token, userid + "");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
        return token;
    }

    /**
     * 根据token删除相关登陆信息
     *
     * @param request
     */
    public static void logout(HttpServletRequest request) {
        Jedis jedis = myJedisPool.getResource();
        try {
            String token = request.getHeader("token") != null ? request.getHeader("token") : request.getParameter("token");
            jedis.hdel(LOGIN_USER_KEY_ + jedis.get(LOGIN_TOKEN_KEY_ + token), token);
            jedis.del(LOGIN_TOKEN_KEY_ + token);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
    }

    /**
     * 校验是否登陆
     *
     * @param request
     * @return
     */
    public static Integer confirm(HttpServletRequest request) {
        Jedis jedis = myJedisPool.getResource();
        Integer userid = null;
        try {
            String token = request.getHeader("token") != null ? request.getHeader("token") : request.getParameter("token");
            if (StringUtils.isNotBlank(token)) {
                String uid = jedis.get(LOGIN_TOKEN_KEY_ + token);
                if (StringUtils.isNotBlank(uid)) {
                    userid = Integer.valueOf(uid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
        return userid;
    }

    /**
     * 保存ios订单支付信息
     *
     * @param userid
     * @return
     */
    public static void savePay(Integer userid,String transaction_id,String money) {
        Jedis jedis = myJedisPool.getResource();

        try {
            jedis.setnx(userid +"_"+ transaction_id , money);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
    }

    /**
     * 判断订单是否已充值成功
     *
     * @param userid
     * @return
     */
    public static boolean confirmPay(Integer userid,String transaction_id) {
        Jedis jedis = myJedisPool.getResource();
        boolean b = false;
        try {
            b = jedis.exists(userid +"_"+ transaction_id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            jedis.close();
        }
        return b;
    }
}
